package com.magina.machine.config.builder;

import com.magina.machine.model.FormMachineData.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;

import java.util.EnumSet;

/**
 * 订单状态机构建器
 */
@Component
public class FormStateMachineBuilder {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private String machineId;

    public String getMachineId() {
        return machineId;
    }

    public void setMachineId(String machineId) {
        this.machineId = machineId;
    }

    /**
     * 构建状态机
     *
     * @param beanFactory
     * @return
     * @throws Exception
     */
    public StateMachine<FormStates, FormEvents> build(String machineId, BeanFactory beanFactory) throws Exception {
        StateMachineBuilder.Builder<FormStates, FormEvents> builder = StateMachineBuilder.builder();
        log.info("==>build {}!", machineId);
        builder.configureConfiguration()
                .withConfiguration()
                .machineId(machineId)
                .beanFactory(beanFactory);

        builder.configureStates()
                .withStates()
                .initial(FormStates.BLANK_FORM)
                .states(EnumSet.allOf(FormStates.class));

        builder.configureTransitions()
                .withExternal()
                .source(FormStates.BLANK_FORM).target(FormStates.FULL_FORM)
                .event(FormEvents.WRITE)
                .and()
                .withExternal()
                .source(FormStates.FULL_FORM).target(FormStates.CONFIRM_FORM)
                .event(FormEvents.CONFIRM)
                .and()
                .withExternal()
                .source(FormStates.CONFIRM_FORM).target(FormStates.SUCCESS_FORM)
                .event(FormEvents.SUBMIT);

        return builder.build();
    }

}